<?php


namespace App\Admin\Controllers\Chart;

// 日结统计
use App\Models\RecordPay;
use App\Models\RecordRecharge;
use Carbon\Carbon;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class DailyChartController
{
	public function index(Content $content, Request $request)
	{
		$param = $request->get('dateTime');
		// 获取参数
		if($param) {
			$timeStart = New Carbon($param);
			$timeEnd = New Carbon($param);
			$time = [$timeStart, $timeEnd->endOfDay()];
		} else {
			$timeStart = New Carbon();
			$timeEnd = New Carbon();
			$time = [$timeStart, $timeEnd->endOfDay()];
		}

		$data= $this->DailyChart($time);
		
		$record = $this->PieChart($time);
		
		$labels = ['现金', '支付宝', '微信', '银行卡', '挂单', '余额', '小程序'];
		
		return $content->title('日结分析')
				->header('日结分析')
				->row(view('admin.chart.daily.datetime-select'))
				->row(function (Row $row) use ($data) {
					$row->column(6, function (Column $column) use ($data) {
						$column->row(view('admin.chart.daily.daily-price-chart', ['title'=> $title = '', 'data' => $data]));
					});
					$row->column(6, function (Column $column) use ($data) {
						$column->row(view('admin.chart.daily.daily-recharge-chart', ['title'=> $title = '', 'data' => $data]));
					});
				})
				->row(function (Row $row) use ($record, $labels) {
					$row->column(8, function (Column $column) use ($record, $labels){
						$column->row(view('admin.chart.daily.daily-type-chart', ['name' => 'type', 'labels' => $labels, 'data' => $record]));
					});
				});
	}
	
	// 日结数据
	public function DailyChart($dateTime)
	{
		$price = RecordPay::whereBetween('created_at', $dateTime)
			->selectRaw('count(*) as count,sum(price) as price')
			->first();
		
		$recharge = RecordRecharge::where('type', 2)
			->whereBetween('created_at', $dateTime)
			->selectRaw('count(*) as count, sum(price) as price')
			->first();
		
		$price->price?$price->price:$price->price = 0;
		$recharge->price?$recharge->price:$recharge->price = 0;
		
		return $data = [
			'price' => $price,
			'recharge' => $recharge
		];
	}
	
	// 日结圆饼图数据
	public function PieChart($dateTime)
	{
		$record = RecordPay::whereBetween('created_at', $dateTime)
			->orderBy('pay_type')
			->get(['price', 'pay_type', 'created_at']);
		
		$res = $record->groupBy('pay_type');
		
		$data = [];
		for ($i = 1; $i <= 7; $i ++) {
			$data[$i] = ['price' => 0];
		}
		
		foreach ($res as $k => $v)
		{
			$price = 0;
			foreach ($v as $key => $value)
			{
				$price += $value['price'];
				$data[$k]['price'] = $price;
			}
		}
		
		return $data;
	}
}